//
//  YHComposeViewController.swift
//  YHWeibo
//
//  Created by yuhao.mac on 16/7/3.
//  Copyright © 2016年 yuhao.mac. All rights reserved.
//

import UIKit

class YHComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        setupNav()
    }

    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        view.addSubview(composeTextView)
        view.addSubview(composeToolBar)
        composeTextView.addSubview(pictureView)
        //添加约束
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(44) 
        }
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(composeTextView).offset(10)
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
        } 
        
        pictureView.composePictureViewClosure = { [weak self] ()->() in
            self?.selectImages()
        }
        
        //监听composeToolBar的按钮点击事件
        composeToolBar.closure = { [weak self] (type: YHComposeToolBarType)->() in
            switch type{
            case .Picture:
                self?.selectImages()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emotion:
                print("表情")
                self?.swtichKeyBoard()
            case .Add:
                print("+")
            }
            
        }
        
        //通过系统通知监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //监听键盘frame的改变
    func keyboardWillChangeFrame(noti: NSNotification){
        
        //NSRect要先转成NSValue再转成CGRect
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        //更新约束
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-(SCREENH - rect.origin.y))
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            //更新布局
            self.view.layoutIfNeeded()
        }
    }

    //使用通知一定要注意移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    //监听事件
    @objc private func cancel(){
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(false, completion: nil)
    }
    @objc private func send(){
        print("发送微博")
        
        if pictureView.imageList.count > 0 {
            upload()
        }else{
            update()
        }
    }
    
    //懒加载控件
    private lazy var titleLabel:UILabel = {
        
        //显示的文字
        let name = YHUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        //最终显示的文字
        let str = "发微博\n\(name)"
        //获取range
        let range = (str as NSString).rangeOfString(name)
        //副文本
        let attr = NSMutableAttributedString(string: str)
        
        //设置副文本
        attr.addAttributes([NSForegroundColorAttributeName:ThemeColor,NSFontAttributeName: UIFont.systemFontOfSize(13)], range: range)
        
        let label = UILabel()
        label.attributedText = attr
        label.textAlignment = .Center
        label.numberOfLines = 0
        label.sizeToFit()
        
        return label
    }()
    
    private lazy var composeTextView:YHComposeTextView = {
        let view = YHComposeTextView()
        view.placeholder = "孟良崮上虎贲垮，千里驰援李天霞。非我见死不相救，奈何共军有高达"
        view.delegate = self
        //允许键盘上下滚动
        view.alwaysBounceVertical = true
        view.font = UIFont.systemFontOfSize(16)
        return view
    }()
    
    private lazy var composeToolBar:YHComposeToolBar = YHComposeToolBar()
    
    private lazy var pictureView:YHComposePictureView = YHComposePictureView()
    
    private lazy var keyboardView:YHEmoticonKeyboard = {
        
        let view = YHEmoticonKeyboard()
        view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        return view
     }()

}

//处理toolBar按钮点击事件
extension YHComposeViewController{
    //选择图片方法
    func selectImages(){
        let picker = UIImagePickerController()
        
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
    //切换键盘方法
    func swtichKeyBoard(){
        if composeTextView.inputView == nil{
            //切换成自定义键盘
            composeTextView.inputView = keyboardView
            
            composeToolBar.isEmotion = true
        }else{
            //代表是自定义键盘，切回系统键盘
            composeTextView.inputView = nil
            //告知toolBar键盘样式
            composeToolBar.isEmotion = false
        }
        
        composeTextView.reloadInputViews()
        //成为第一响应者
        composeTextView.becomeFirstResponder()
    }
    
}

extension YHComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        
//        let data = UIImagePNGRepresentation(scaleImageOfWidth(400, image: image))
//        data?.writeToFile("/Users/mac.yu/Desktop/123.png", atomically: true)
        
        //把图片传给pictureView
        pictureView.addImages(scaleImageOfWidth(400, image: image))
        //如果实现了代理方法，系统不会帮我们关闭控制器
        picker.dismissViewControllerAnimated(false, completion: nil)
    }
    
    //压缩图片的方法
    func scaleImageOfWidth(width: CGFloat, image:UIImage)->UIImage{
        if width > image.size.width{
            return image
        }
        let height = width * (image.size.height/image.size.width)
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        //开启图形上下文对象
        UIGraphicsBeginImageContext(rect.size)
        //将image渲染到图形上下文对象中
        image.drawInRect(rect)
        let result = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文对象
        UIGraphicsEndImageContext()
        return result
    }
}


//发送微博的请求
extension YHComposeViewController{
    //发送文字微博
    func update(){
        YHNetworkTools.sharedTools.composeUpdate(composeTextView.text, success: { (response) -> () in
            print("发送成功")
            }) { (error) -> () in
                print("发送失败")
        }
    }
    //上传图片和文字微博
    func upload(){
        YHNetworkTools.sharedTools.comoposeUpload(composeTextView.text, imageList: pictureView.imageList, success: { (response) -> () in
            print("发送成功")
            }) { (error) -> () in
                print("发送失败")
        }
    }
}

extension YHComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    //滚动的时候让键盘辞去第一响应者
    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }
}

















